'use strict';
function now() {
  return parseInt(Number(new Date()) / 1000, 10);
}
module.exports = app => {
  const { STRING, DATE } = app.Sequelize;

  const AccessToken = app.model.define('accessToken', {
    accessToken         : { type: STRING, unique: true },
    accessTokenExpiresAt: DATE,
    scope               : STRING,
    clientId            : STRING,
    userId              : { type: STRING, allowNull: false },
  }, {
    createdAt: 'createdAt',
    updatedAt: 'updatedAt',
    tableName: 'zconnect-accesstoken',
  });
  // 查找一个用户未过期的accessToken
  AccessToken.getAccessTokenByUser = async function(userId) {
    return this.findOne({
      where: {
        userId,
        accessTokenExpiresAt: {
          [app.Sequelize.Op.gt]: now(),
        } },
    });
  };

  // 搜索accessToken
  AccessToken.getAccessTokenByToken = async function(bearerToken) {
    return this.findOne({
      where: { accessToken: bearerToken },
    });
  };

  // 保存accessToken
  AccessToken.saveAccessToken = async function(token, client, user) {
    await this.create({
      accessToken         : token.accessToken,
      accessTokenExpiresAt: token.accessTokenExpiresAt,
      clientId            : client.clientId,
      userId              : user.lid,
      scope               : token.scope || '',
    });
  };

  return AccessToken;
};
